package com.qqt.csr.file.service.impl;

import cn.hutool.core.io.FileUtil;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.qqt.csr.common.enums.FileGroupEnum;
import com.qqt.csr.common.enums.FileTypeEnum;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.file.service.IFileFolderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

@Slf4j
@Service
public class FileFolderHWOBSServiceImpl extends AbstractHWOBSService implements IFileFolderService {

    /**
     * 获取文件存储路径
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    @Override
    public String getFileFolder(String bucketName, String objectName) {
        ServiceAssert.isTrue(StringUtils.isNotBlank(objectName), StatusCode.Common.NULL_ERROR.getCode(), "文件名不能为空");
        String extension = FileUtil.getSuffix(objectName);
        ServiceAssert.isTrue(StringUtils.isNotBlank(extension), StatusCode.Common.NULL_ERROR.getCode(), "不支持当前文件类型");
        FileTypeEnum fileType = FileTypeEnum.of(extension);
        ServiceAssert.notNull(fileType, StatusCode.Common.ILLEGAL.getCode(), "不支持当前文件类型");
        return getFileFolder(bucketName, fileType);
    }

    /**
     * 获取文件存储路径
     *
     * @param bucketName
     * @param fileType
     * @return
     */
    @Override
    public String getFileFolder(String bucketName, FileTypeEnum fileType) {
        ServiceAssert.notNull(fileType, StatusCode.Common.ILLEGAL.getCode(), "不支持当前文件类型");
        return createFileFolderBy(bucketName, fileType.getGroup());
    }

    /**
     * 创建文件夹
     *
     * @param bucketName
     * @param fileGroup
     * @return
     */
    @Override
    public String createFileFolderBy(String bucketName, FileGroupEnum fileGroup) {
        if (!obsClient.doesObjectExist(bucketName, rootFolder)) {
            PutObjectResult result = obsClient.putObject(bucketName, rootFolder, new ByteArrayInputStream(new byte[0]));
            ServiceAssert.isTrue(isRequestSuccess(result), StatusCode.Common.THIRD_API_ERROR.getCode(), "创建文件夹失败");
        }
        String folderName = rootFolder + fileGroup.name().toLowerCase() + "/";
        if (obsClient.doesObjectExist(bucketName, folderName)) {
            return folderName;
        }
        PutObjectResult result = obsClient.putObject(bucketName, folderName, new ByteArrayInputStream(new byte[0]));
        ServiceAssert.isTrue(isRequestSuccess(result), StatusCode.Common.THIRD_API_ERROR.getCode(), "创建文件夹失败");
        return folderName;
    }
}
